# -*- coding: UTF-8 -*-
# cython: language_level=3
import time
from datetime import datetime

from db.elastic_search import ES
from db.mongodb import MongoDB
from db.mysqldb import MysqlDB

es = ES()
db = MongoDB()
mysql_client = MysqlDB()


class Export():
    def __init__(self, site_info):
        self.site_id = site_info['_id']
        self.site_info = site_info

    def save_oracle(self):
        sql = ('INSERT INTO TAB_VIDEO_SITE_INFO ('
               'SITE_NAME,URL,SITE_TYPE,AUTO_RECORD_NUMBER,IP_ADDRESS,'
               f'CITY_NAME,PROVINCE_NAME,FIND_DATE,DOMAIN) VALUES ({",".join("%s" for i in range(9))})')
        result = mysql_client.add(sql, (
            self.site_info['title'], self.site_info['home_page'], 3, self.site_info['icp'], self.site_info['IP'],
            self.site_info['CITY_NAME'], self.site_info['PROVINCE_NAME'], datetime.now(), self.site_info['host']))
        if not result:
            self.oid = mysql_client.find('SELECT id FROM TAB_VIDEO_SITE_INFO WHERE DOMAIN=%s',
                                         args=(self.site_info['host'],), fetch_one=True)[0]
            assert self.oid
            db.update('WEB_urls', {'_id': self.site_id}, {'oid': self.oid, 'export_status': True})

        else:
            self.oid = result
            db.update('WEB_urls', {'_id': self.site_id}, {'oid': self.oid, 'export_status': True})

    def save_es(self, min_Confidence):
        db.update('WEB_urls', {'_id': self.site_id}, {'min_confidence': min_Confidence})


def auto_export(status=None):
    if status:
        url_dict = {'status': status}
    else:
        url_dict = {"$and": [{"export_status": {"$exists": False}}, {"site_Confidence": {"$gt": 10000}}]}
    for i in db.find('WEB_urls', url_dict):
        export = Export(i)
        result = export.save_oracle()
        print(result)


def k_export(mid=None):
    export = Export(mid)
    result = export.save_oracle()
    print(result)
    if result:
        print(export.save_es(2000))


def man_export():
    mid = input('请输入要导入的mongoid,并按回车确认： ')
    export = Export(mid)
    status_y = input(f"请确认标题是否为【{export.site_info['title']}】, y/n ?")
    if status_y == 'y':
        result = export.save_oracle()
        print(result)
        status_y = input(f"是否导出节目单, y/n ?")
        if status_y == 'y':
            while True:
                try:
                    min_Confidence = int(input(f"请输入置信度下限： "))
                except:
                    print(f"输入有误,请重新输入置信度下限： ")
                else:
                    break

            if result:
                print(export.save_es(min_Confidence))
    time.sleep(100)


if __name__ == '__main__':
    auto_export()

    # man_export()
    # k_export(mid='64947a99f6ae302f4d57300c')

    # screen_shot()
